package com.ecole.mines.emargement;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTPClient;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.ecole.mines.model.Eleve;
import com.ecole.mines.model.Promotion;
import com.ecole.mines.utils.Connexion;
import com.ecole.mines.utils.FTP;
import com.ecole.mines.utils.OnTaskCompleted;
import com.ecole.mines.utils.ParserJSONEleve;
import com.ecole.mines.utils.UtilsString;
import com.ecole.mines.utils.WriteJSON;

public class EmargementActivity extends FragmentActivity implements
		OnTaskCompleted {

	private ProgressDialog spinnerLoadData;
	private FragmentListeEleves fragListeEleve;
	private FragmentInformationsTop fragInfoTop;
	private WriteJSON writeJSON;
	private Promotion promotion;
	private ArrayList<Eleve> listeEleves;
	private boolean retourEmargement;
	private SharedPreferences sharedpreferences;

	@Override
	public void onBackPressed() {
		verifCodePin();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_emargement);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		this.promotion = getIntent().getExtras().getParcelable("promo");

		fragListeEleve = (FragmentListeEleves) getFragmentManager()
				.findFragmentById(R.id.fragmentListeEleves);
		fragInfoTop = (FragmentInformationsTop) getFragmentManager()
				.findFragmentById(R.id.fragment3);
		fragInfoTop.majInfo(this.promotion);
		
		sharedpreferences = getSharedPreferences(UtilsString.MyPREFERENCES,
					Context.MODE_PRIVATE);
		Editor editor = sharedpreferences.edit();
		editor.putBoolean("emargement",true);
		editor.commit();
			
		this.writeJSON = new WriteJSON(this.promotion);
		this.setRetourEmargement(false);

		showLoadingDialog("Chargement des élèves");
		new ParserJSONEleve(this).execute("/tablette/eleves", promotion
				.getCours().get(0).getGroupe());

	}

	@SuppressWarnings("unchecked")
	@Override
	public void onTaskCompletedPromo(ArrayList<?> eleves) {
		this.listeEleves = (ArrayList<Eleve>) eleves;
		this.writeJSON.chargerEleves(this.listeEleves);
		fragListeEleve.majListeEleve((ArrayList<Eleve>) eleves);
		dismissLoadingDialog();
	}

	public void showLoadingDialog() {

		if (spinnerLoadData == null) {
			spinnerLoadData = new ProgressDialog(this);
			spinnerLoadData.setTitle("Chargement");
			spinnerLoadData
					.setMessage("Interrogation du serveur d'Authentification");
		}
		spinnerLoadData.show();
	}

	public void showLoadingDialog(String message) {

		if (spinnerLoadData == null) {
			spinnerLoadData = new ProgressDialog(this);
			spinnerLoadData.setTitle("Chargement");
		}
		spinnerLoadData.setMessage(message);
		spinnerLoadData.show();
	}

	public void dismissLoadingDialog() {
		if (spinnerLoadData != null && spinnerLoadData.isShowing()) {
			spinnerLoadData.dismiss();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_signature, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			verifCodePin();
			return true;
		case R.id.action_envoi:
			// traitementSignature();
			envoyerJsonServeur();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void enregistrerEleveJson(Eleve eleve) {
		if (!this.writeJSON.rechercherEleve(eleve)) {
			if (!this.writeJSON.enregistrerEleve(eleve)) {
				Toast.makeText(this, "L'élève n'a pas pu être ajouté.",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			if (!this.writeJSON.modifierEleve(eleve)) {
				Toast.makeText(this, "L'élève n'a pas pu être modifié.",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public void envoyerJsonServeur() {
		// this.writeJSON.printJson();
		this.writeJSON.setListeEleves(this.listeEleves);
		this.writeJSON.execute();

	}

	public void executerCo(String value) {
		Connexion co = new Connexion(this);
		co.execute(value.toString());
	}

	public void verifCodePin() {
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);

		new AlertDialog.Builder(this)
				.setTitle("Menu protégé")
				.setMessage("Entrez le code pin")
				.setView(input)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Editable value = input.getText();
						// Envoyer le code saisi au serveur
						// Récupérer la réponse
						showLoadingDialog("Interrogation du serveur d'Authentification");
						executerCo(value.toString());
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								dialog.cancel();
							}
						}).show();
	}

	public void retourEcranAccueil() {
		dismissLoadingDialog();
		setRetourEmargement(true);
		Editor editor = sharedpreferences.edit();
		editor.putBoolean("emargement",false);
		editor.commit();
		this.finish();
	}

	public void confirmChangementEleve(
			final FragmentCadreSignature cadreSignature,
			final Eleve eleveSelectionne, final Bitmap signatureBitmapSave) {

		new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Validation de la signature")
				.setMessage(
						"La signature n'a pas été enregistrée. Souhaitez-vous la valider avant de changer ?")
				.setPositiveButton("Valider la signature",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								// Stop the activity
								cadreSignature.enregistrerSignature(
										eleveSelectionne, signatureBitmapSave);
							}

						})
				.setNegativeButton("Annuler la signature",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								cadreSignature.effacerSignature();

							}
						}).show();

	}

	@Override
	public void onTaskCompletedPin(Boolean resultat) {
		if (resultat) {
			retourEcranAccueil();
		} else {
			Toast.makeText(getApplication(), "Code incorrect",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void setPromotion(Promotion promotion) {
		this.promotion = promotion;
	}

	public Promotion getPromotion() {
		return this.promotion;
	}

	private void envoiFTP() {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {

					String server = "91.121.167.164";
					int port = 21;
					String user = "desktop";
					String pass = "opsys34!";

					FTPClient ftpClient = new FTPClient();

					try {
						// connect and login to the server
						ftpClient.connect(server, port);
						ftpClient.login(user, pass);

						// use local passive mode to pass firewall
						ftpClient.enterLocalPassiveMode();

						System.out.println("Connected");

						String remoteDirPath = "/Emargement";
						String localDirPath = Environment.getExternalStorageDirectory().getPath();

						FTP.uploadDirectory(ftpClient, remoteDirPath,
								localDirPath, "");

						// log out and disconnect from the server
						ftpClient.logout();
						ftpClient.disconnect();

						System.out.println("Disconnected");
					} catch (IOException ex) {
						ex.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		thread.start();
	}

	@Override
	public void onStop() {
		super.onStop();
		System.out.println("on stop");
		// Si l'activité n'est pas arrêté par un retour utilisateur
		// On sauvegarde les données
		if (!this.isRetourEmargement()) {
			sharedpreferences = getSharedPreferences(UtilsString.MyPREFERENCES,
					Context.MODE_PRIVATE);
			Editor editor = sharedpreferences.edit();
			editor.putString("key", "value");
			editor.commit();
		}
	}

	public boolean isRetourEmargement() {
		return retourEmargement;
	}

	public void setRetourEmargement(boolean retourEmargement) {
		this.retourEmargement = retourEmargement;
	}

}
